#include "file.h"
#include"item.h"
#include<string>
#include<fstream>
#include<iostream>
#include<iomanip>
#include <map>
#include <stdexcept>
#include<cstdlib>
using namespace std;

fstream file::target("fmgrdata.txt", ios::in );

int file::read_init(string file_name)
{
	if (target.is_open())
	{
		target.close();
	}
	target.open(file_name,ios::in);
	if (!target)
	{
		fstream blankFile("fmgrdata.txt",ios::out);
		blankFile << 0;
		blankFile.close();
		target.open(file_name, ios::in);
	}
	int ids;
//	target.seekg(0);
//	target.read(reinterpret_cast<char*>(&ids), sizeof(ids));
	target >> ids;
	return ids;
}

void file::write_init(int ids, string file_name)
{
	target.open(file_name,ios::out);//attention
	target << ids << std::endl;
}

basic_item* file::read()
{
	basic_item* item1;

	map<string, string> temp;
	string cur = "";

	do
	{
		getline(target, cur);

		if (target.eof())
		{
			return nullptr;
		}
	}
	while (cur != "{");

	while (getline(target, cur))
	{
		if (cur == "}")
			break;

		int pos = cur.find(':');
		temp[cur.substr(0, pos)] = cur.substr(pos + 2);
//		std::cout << "--- " << cur.substr(0, pos) << ": " << cur.substr(pos + 2) << std::endl;
	}

	if (temp["type"] == "activity")
	{
		item1 = new activity;
		item1->database_input(temp);
	}
	else if (temp["type"] == "task")
	{
		item1 = new task;
		item1->database_input(temp);
	}
	else
	{
		throw std::invalid_argument("Unknown item type: " + temp["type"]);
	}

	return item1;
}

void file::write(basic_item* item1)
{
	string rec=item1->to_db_str();
	target<<rec;
}

void file::close()
{
	target.close();
}